import React from 'react';
import { Table, Input,Button,Divider ,Popconfirm,message,Select} from 'antd';
import '../../assets/css/system.css';
import store from '../../store';
import { $http } from '../../containers/config/https';
import TarSubTypeModal from './TarSubTypeModal.jsx';

import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const Option = Select.Option;
export default class TarSubTypeMenu extends React.Component{
    /***初始化变量***/
    constructor(props){
        super(props);
        this.state={
            code:'',
            desc:'',
            userInfo: {},
            // 主菜单列表数据
            data: [],
            // 抽屉显示
            visible: false,
            // 主菜单分页数据
            total: 0,
            page: 1,
            pageSize: 10,
            flag: '',
            title: '',
            // 是否显示loading
            showLoading: true,
            // 表格loading
            loading: true,
            hospList:[],
            hospID:'',
            tarTypeList:[],
            hospID:'',
            tarTypeID:'',

            columns: [],
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识

        }
        //table列名
        // this.columns=[
        //     {
        //         title:"子类代码",
        //         dataIndex:'code',
        //         width:'100px',
        //         align:'center',
        //     },
        //     {
        //         title:'子类名称',
        //         dataIndex:'descripts',
        //         width:'100px',
        //         align:'center'

        //     },
        //     {
        //         title: '操作',
        //         dataIndex: 'operation',
        //         align: "center",
        //         width: 150,
        //         render: (text,record) => (
        //             <span>
        //                 <span className='span' onClick={this.handleCompile.bind(this, record)}>修改</span>
        //                 <Divider type="vertical" />
        //                 <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDetele.bind(this, record)} >
        //                     <span className='span'>删除</span>
        //                 </Popconfirm>
        //             </span>
        //         )
        //     },
        //     {
        //         title:"类型-大类名称",
        //         dataIndex:"typeAndTarTypeDesc",
        //         width:'100px',
        //         align:'center'
        //     },
        //     {
        //         title:"创建日期",
        //         dataIndex:"createDate",
        //         width:'100px',
        //         align:'center'
        //     },
        //     {
        //         title:"创建人",
        //         dataIndex:"createUserName",
        //         width:'100px',
        //         align:'center'
        //     }
        //     ,
        //     {
        //         title:"医院",
        //         dataIndex:"hospName",
        //         width:'100px',
        //         align:'center'
        //     }
        // ]
    }

    /***生命周期方法 ***/
    componentDidMount() {
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};

        this.tableList("TarSubTypeMenu","TarSubTypeMenu");

        this.setState({hospID:sessionInfo.hospID}, () => {
            this.handleQuery();
            this.handleHospQuery();
            this.handleTarTypeQuery();
        });
         // 初始化设置table的高度以及表体的高度
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
         // 数据异步请求，请求成功之后setState
		this.setState({
			showLoading: false
		})
    }
    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }    
    }
    /* componentWillUnmount() {
        this.setState = (state,callback)=>{ return; }; 
        // 组件销毁前清除监听
        //window.removeEventListener('resize', this.handelHeight);
    }*/
    
//render 自定义项目名称
listAdd = (i, j, languageCode) => {
    let { columns } = this.state
    columns.splice(i, j,
      {
        title: languageCode === 'CN' ? "操作" : 'Operation',
        key: 'op',
        align: "center",
        render: (text,record) => (
            <span>
                <span className='span' onClick={this.handleCompile.bind(this, record)}>{languageCode === 'CN' ? "修改" : 'Alter'}</span>
                <Divider type="vertical" />
                <Popconfirm 
                    title={languageCode === 'CN' ? "确定要删除吗?" : 'You sure you want to delete it?'} 
                    onConfirm={this.handleDetele.bind(this, record)} 
                    okText={languageCode === 'CN' ? "是" : 'Yes'}
                    cancelText={languageCode === 'CN' ? "否" : 'No'}
                >
                    <span className='span'>{languageCode === 'CN' ? "删除" : 'Delete'}</span>
                </Popconfirm>
            </span>
        )
      },
    )
  }
  onColumnRef = (ref) => {
    console.log(ref)
    this.columnRef = ref;
  }
  // 获取主列表columns
  tableList = (reactCode, compontName) => {
    var data = {
      params: [{
          "reactCode": [reactCode],
          "compontName": compontName,
          "type": "C"
      }]
  }
    console.log(1, data)
    $http.post('urlS', this, {
        code: '01040073',
        data: data,
        success: function (res) {
            if (+res.errorCode === 0) {
                let resC = res.result.C
                let { languageCode } = this.state
                for (var i = 0; i < resC.length; i++) {
                    resC[i].key = i;
                }
                if (languageCode === "EN") {
                    resC.map((item, i) => {
                        item.title = item.enDescripts
                    })
                }
            
                if (languageCode === "CN") {
                    resC.map((item, i) => {
                        item.title = item.descripts
                    })
                }
                let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
                    return {
                        align: item.align,
                        widthNum: parseInt(item.width),
                        width: item.width,
                        dataIndex: item.dataIndex,
                        title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                        display: item.display,
                        key: item.seqNo
                    }
                }) : '';
                let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                this.setState({ 
                  columns: filterArr,
                  languageTable1: res.result.B || {},  // 国际化Table1
                  languageTable2: res.result.C || {},  // 国际化Table2
                  languageData: res.result.language || {},  // 国际化语言包
                }, () => {
                  this.LanCNEN(this.state.languageCode)
                  this.listAdd(filterArr.length+1, 0,languageCode);
                })
            }
        }
    })
  }

  LanCNEN = (code) => {
    let { languageData } = this.state
    this.setState({
        language: languageData[code]
    })
  }

// 页码改变的回调，参数是改变后的页码及每页条数
  appPageChange = (page, pageSize) => {
    this.setState({
        page: page,
        pageSize: pageSize,
    }, () => {
        // 重新调用查询方法
        this.handleQuery();
    });
  }

  // 条数改变的回调
  apponShowSizeChange = (current, size) => {
    this.setState({
        page: current,
        pageSize: size,
    }, () => {
        // 重新调用查询方法
        this.handleQuery();
    });
  }


    /***下拉框方法***/
    handleHospQuery = () => {
        let data = {}
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        data = {
            params: [{
            hospitalId:"",
            logonGroupID:sessionInfo.groupID,
            logonHospID:sessionInfo.hospID,
            hospRequired:"1",
            }]
        }
        $http.post('urlS', this, {
            code: '01040001',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.depDoctor) {
                    let tempList =[];
                    for (var i = 0; i < res.depDoctor.length; i++) {
                        tempList.push(<Option key={res.depDoctor[i].id}>{res.depDoctor[i].descripts}</Option>)
                    }
                    this.setState({
                    hospList: tempList
                    })
                } 
            }
        })
    }   

     // 收费项大类下拉框
     handleTarTypeQuery = () => {
        let data = {}
        let {hospID}=this.state
        data = {
            params: [{
            code: "",
            descripts: "",
            hospID:hospID,
            }]
        }
        $http.post('urlS', this, {
            code: '05100014',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.tarType) {
                    let tempList =[];
                    for (var i = 0; i < res.tarType.length; i++) {
                        tempList.push(<Option key={res.tarType[i].tarTypeID}>{res.tarType[i].typeAndTarTypeDesc}</Option>)
                    }
                    this.setState({
                    tarTypeList: tempList
                    })
                } 
                /*else {
                    setTimeout(() => {
                        this.setState({ tarTypeList: [] })
                    }, 1000)
                }*/
            }
        })
    }
    
    


    /***双向绑定方法***/
    onChangeCode=(e)=>{
        this.setState({
            code:e.target.value
        })
    }
    onChangeDesc=(e)=>{
        this.setState({
            desc:e.target.value
        });
    }
    onChangeHospID=(value)=>{
        this.setState({
            hospID:value
        }, () => {
            this.handleTarTypeQuery();
        });
    }
    onChangeTarTypeID=(value)=>{
        this.setState({
            tarTypeID:value
        });
    }




    /***其他方法***/
    //页码改变的回调，参数是改变后的页码及每页条数
    onChange=(page, pageSize)=> {
        this.setState({page: page, pageSize: pageSize}, () => {
            // 重新调用查询方法
            this.handleQuery();
     });
    }
    // 重置userInfo
    resetUserInfo() {
        this.setState({userInfo: {}})
    }
    // 调用子组件的连接事件
     onRef = (ref) => {
        this.child = ref
    }




    /***增删改查****/
    // 查询
    handleQuery = () => {
        let {code, desc, page, pageSize,hospID,tarTypeID} = this.state;
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {}
        if (code || desc) {
            data = {
                params: [{
                    code: code,
                    descripts: desc,
                    hospID:hospID,
                    tarTypeID:tarTypeID
                }],
                pagination:[{
                    pageSize: 10,
                    currentPage: 1,
                    sortColumn: "Code",
                    sortOrder: "asc"
                }]
            }
        } else {
            data = {
                params: [{
                    code: code,
                    descripts: desc,
                    hospID:hospID,
                    tarTypeID:tarTypeID
                }],
                pagination:[{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: "Code",
                    sortOrder: "asc"
                }]
            }
        }
        console.log(data);
        $http.post('urlS', this, {
          code: '05100018',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0 && res.tarSubType) {
              for(var i = 0; i < res.tarSubType.length; i++) {
                res.tarSubType[i].key = i;
              }
              this.setState({data: res.tarSubType, total: res.total, loading:false})
            } 
            /*else {
                setTimeout(() => {
                    this.setState({data: [], total: 0, loading: false})
                }, 3000)
            }*/
          }
        })
    }
    //增加方法
    handleAdd=()=>{
            // 显示弹框
            this.child.showModal()
            // 初始化数据
            this.setState({flag: 'add', title: '新增'})
    }
    //修改方法
    handleCompile(record) {
            // 重置form表单
            this.child.resetFields()
            // 打开弹框
            this.child.showModal();
            // 初始化数据
            this.setState({flag: 'compile', userInfo: record, title: '编辑'});
        }
    // 删除
    handleDetele(record) {
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let updateUserID =sessionInfo.userID;
        let data = {
            params: [{
                tarSubTypeID: record.tarSubTypeID,
                updateUserID:updateUserID
            }]
        }
        $http.post('urlADS', this, {
            code: '05100021',
            data: data,
            success: function (res) { 
                   
                if (+res.errorCode === 0) {
                    message.success('删除成功');
                    this.handleQuery()
                } else {
                    message.error('删除失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('删除失败：' + error);
            }
        })
    }
   
    render(){
        let {language}=this.state
        return(
            <div>
               < div >
               {language.TarSubTypeMenucode && language.TarSubTypeMenucode.descripts}： <Input placeholder={language.TarSubTypeMenucode && language.TarSubTypeMenucode.message} style={{width:'150px'}} value={this.state.code} onChange={this.onChangeCode}/>
               {language.TarSubTypeMenudescripts && language.TarSubTypeMenudescripts.descripts}： <Input placeholder={language.TarSubTypeMenudescripts && language.TarSubTypeMenudescripts.message} style={{width:"150px"}} value={this.state.desc} onChange={this.onChangeDesc}/>
               {language.TarSubTypeMenuhospital && language.TarSubTypeMenuhospital.descripts}： <Select
                    showSearch
                    allowClear
                    placeholder={language.TarSubTypeMenuhospital && language.TarSubTypeMenuhospital.message}
                    optionFilterProp="children"
                    style={{width:"150px"}}
                    value={this.state.hospID}
                    onChange={this.onChangeHospID}
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >{this.state.hospList}</Select>
               {language.TarSubTypeMenutarType && language.TarSubTypeMenutarType.descripts}：<Select
                    showSearch
                    allowClear
                    placeholder={language.TarSubTypeMenutarType && language.TarSubTypeMenutarType.message}
                    style={{width:"200px"}}
                    optionFilterProp="children"
                    value={this.state.tarTypeID}
                    onChange={this.onChangeTarTypeID}
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >{this.state.tarTypeList}</Select>
               <Button type="primary"  onClick={this.handleQuery} style={{marginLeft:'30px'}}>{language.TarSubTypeMenuquery && language.TarSubTypeMenuquery.descripts}</Button>
               <Button type="primary"  onClick={this.handleAdd} style={{marginLeft:'30px'}}>{language.TarSubTypeMenuadd && language.TarSubTypeMenuadd.descripts}</Button>
               
                <Table
                    style={{height: store.getState().tableHeight.y + 45 + 'px',marginTop:'30px'}}
                    dataSource={this.state.data}
                    columns={this.state.columns}
                    className='TableA'
                    //rowClassName="editable-row"
                    pagination={false}
                    scroll={{ x: 1500, y: store.getState().tableHeight.y }}
                    bordered
                    loading={this.state.loading}
                />
                <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
                    onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.data}
                    onChange={this.appPageChange} />
                <ColumnAuthoritysModel
                    clientWidth='900px'
                    compontName='TarSubTypeMenu'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.tableList}
                />


               </div>
               <TarSubTypeModal
               onRef={this.onRef}
               userInfo={this.state.userInfo}
               flag={this.state.flag}
               handelThis={this}
               title={this.state.title}
               />
            </div>
        )
    }
     

}